package com.example.online.utils;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;


//工具类
public class MybatisUtils {
    private static SqlSessionFactory SqlSessionFactory = null;

    static {
        try {
            String resource = "sqlMapConfig.xml";//获取配置文件
            Reader reader = Resources.getResourceAsReader(resource);//读取配置文件
            SqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);//通过配置文件获得连接对象
        } catch (IOException e) {
            System.out.println("MyBatis类读取文件报错啦");
        }
    }

    //获取sqlSession对象的静态方法
    public static SqlSession getSession(){
        return SqlSessionFactory.openSession();
    }

    //获取sqlSession对象的静态方法
    public static SqlSession getSession(boolean isAutoCommit){
        return SqlSessionFactory.openSession(isAutoCommit);
    }


    //关闭连接对象的静态方法
    public static void closeSession(SqlSession sqlSession){
        sqlSession.commit();
        sqlSession.close();
    }
}
